package yl.hs.bmipfull.service.salemanage.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.controllers.material.PurchaseContractPriceAdjustDocController;
import yl.hs.bmipfull.daos.laboratory.IProductInfoDao;
import yl.hs.bmipfull.daos.material.IPurchaseContractPriceAdjustmentDao;
import yl.hs.bmipfull.daos.salemanage.IContractPriceAdjustDocDao;
import yl.hs.bmipfull.daos.salemanage.IContractPriceAdjustmentDao;
import yl.hs.bmipfull.daos.salemanage.ISaleContractDao;
import yl.hs.bmipfull.daos.salemanage.ISaleContractProductsDao;
import yl.hs.bmipfull.pojo.material.PurchaseContractPriceAdjustDocEntity;
import yl.hs.bmipfull.pojo.salemanage.ContractPriceAdjustDocEntity;
import yl.hs.bmipfull.pojo.salemanage.ContractPriceAdjustmentEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleContractProductsEntity;
import yl.hs.bmipfull.service.impl.BaseService;
import yl.hs.bmipfull.service.salemanage.IContractPriceAdjustDocService;
import yl.hs.bmipfull.service.salemanage.IContractPriceAdjustmentService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.salemanmage.SaleContractPriceAdjustViewModel;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 作用:  销售合同调价单服务层接口实现<br/>
 * 创建时间: 2021年06月03日 09时12分21秒 <br/>
 *
 * @author 张凯
 */
@Service
public class ContractPriceAdjustDocServiceImpl extends SaleBaseService implements IContractPriceAdjustDocService {

    @Autowired
    IContractPriceAdjustDocDao dao;

    @Autowired
    IContractPriceAdjustmentService adjustmentService;
    @Autowired
    ISaleContractDao saleContractDao;
    @Autowired
    IContractPriceAdjustmentDao adjustmentDao;
    @Autowired
    IProductInfoDao productInfoDao;

    @Override
    public List<ContractPriceAdjustDocEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(ContractPriceAdjustDocEntity.class);
        return dao.queryList(pageQuery.getQuery());
    }

    @Override
    public PageResult<ContractPriceAdjustDocEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(ContractPriceAdjustDocEntity.class);

        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<ContractPriceAdjustDocEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(), ContractPriceAdjustDocEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(), filters));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery(), filters));
        return result;
    }


    @Override
    public SaleContractPriceAdjustViewModel getBySn(String sn) {
        ContractPriceAdjustDocEntity entity = dao.findBySN(sn);
        SaleContractPriceAdjustViewModel result = new SaleContractPriceAdjustViewModel();
        if (entity != null) {
            result.setId(entity.getId());
            result.setContractSN(entity.getContractSN());
            result.setContractName(saleContractDao.findContractNameBySn(entity.getContractSN()));
            result.setHandlerTime(entity.getHandlerTime());
            result.setSn(entity.getSn());
            result.setHandlerName(entity.getHandlerName());
            result.setRemark(entity.getRemark());
            result.setHandlerSN(entity.getHandlerSN());
            result.setState(entity.getState());
            result.setAdjustment(adjustmentDao.queryListByDocSn(entity.getSn()));
        }
        return result;
    }

    @Override
    @Transactional
    public Integer saveContractPriceAdjustDoc(Map<String, Object> model, String sn) throws Exception {
        Integer result = 0;
        var user=HsApp.getCurrent();
        ContractPriceAdjustDocEntity entity = new ContractPriceAdjustDocEntity();
        if (Tl.isEmpty(sn)) {
            //执行保存
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            sn = queryNewSN(ContractPriceAdjustDocEntity.class);
            entity.setSn(sn);
            entity.setHandlerName(user.getUserName());
            entity.setHandlerSN(user.getUserSN());
            entity.setHandlerTime(new Date());
            result = dao.insertNew(entity);
            if (result > 0) {
                writeLog(ActionType.CREATE, entity.getSn(), "插入销售合同调价单信息", Tl.toJson(entity), ContractPriceAdjustDocEntity.class);
            }

        } else {
            //执行修改
            entity = dao.findBySN(sn);
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setHandlerTime(new Date());
            result = dao.update(entity);

            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, "更新销售合同调价单信息", Tl.toJson(entity), ContractPriceAdjustDocEntity.class);
            }
        }
        // 调价单明细信息
        if (result > 0) {
            List<Map<String, Object>> adjustment = (List<Map<String, Object>>) model.get("adjustment");
            if (adjustment != null) {
                adjustmentService.saveContractPriceAdjustment(adjustment, sn);
            }

        }
        return result;
    }

    @Override
    @Transactional
    public Integer delete(String[] sn) {
        Integer result = dao.changeStateBySN(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, ContractPriceAdjustDocEntity.class);
        }
        return result;
    }

    @Override
    public Integer changeStateBySN(String[] snArray, short state) {
        int result = dao.changeStateBySN(snArray, state);
        if (result > 0) {
            forWriteLog(snArray, state);
        }
        return result;
    }

    @Autowired
    IContractPriceAdjustDocService service;
    @Autowired
    ISaleContractProductsDao productsDao;

    @Override
    public Integer batchPriceAdjustment(Map<String, Object> model, String sn) throws Exception {
        var user = HsApp.getCurrent();
        Integer result = 0;

        var all = productsDao.getAll(sn);
        if (all.size() == 0) {
            result = -1;
            return result;
        }
        //主表
        ContractPriceAdjustDocEntity doc = new ContractPriceAdjustDocEntity();
        doc.setHandlerSN(user.getUserSN());
        doc.setHandlerName(user.getUserName());
        doc.setHandlerTime(new Date());
        doc.setContractSN(sn);
        doc.setSn(queryNewSN(ContractPriceAdjustDocEntity.class));
        doc.setState((short) 2);
        doc.setRemark((String) model.get("cause") );
        dao.insertNew(doc);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        var startTimeStr=(String) model.get("startTime");
        var startTime=sdf.parse(startTimeStr);
        for (var product: all) {
            //子表
            ContractPriceAdjustmentEntity entity = new ContractPriceAdjustmentEntity();
            entity.setAdjustDocSN(doc.getSn());
            entity.setSn(queryNewSN(ContractPriceAdjustmentEntity.class));
            entity.setStartTime(startTime);
            entity.setOriginalPrice(product.getPrice());
            entity.setContractProductSN(product.getSn());
            entity.setCause((String) model.get("cause"));
            if(model.get("modifyPrice") != null){
                BigDecimal modifyPrice= BigDecimal.valueOf(Double.parseDouble(model.get("modifyPrice").toString()));
                entity.setModifyPrice(modifyPrice.floatValue());
                entity.setCurrentPrice(entity.getOriginalPrice()+modifyPrice.floatValue());
            }else if(model.get("adjustScale") != null){
                BigDecimal adjustScale= BigDecimal.valueOf(Double.parseDouble(model.get("adjustScale").toString()));
                entity.setAdjustScale(adjustScale.floatValue());
                entity.setCurrentPrice(entity.getOriginalPrice()*(1+adjustScale.floatValue()/100));
            }else{
                return -1;
            }
            result=adjustmentDao.insertNew(entity);
        }
        writeLog(ActionType.CREATE, doc.getSn(), "插入销售合同调价单信息", Tl.toJson(doc), ContractPriceAdjustDocEntity.class);
        return result;
    }

    @Override
    public Integer batchProductPriceAdjustment(Map<String, Object> model, String sn) throws ParseException {
        var user=HsApp.getCurrent();
        Integer result = 0;
        var contractSNList=productsDao.getContractSNByProductSN(sn);
        var list = productInfoDao.queryContractProductPrice(contractSNList,sn,new Date(),"");
        if (contractSNList !=null && contractSNList.size()>0){
            for (var contractSN:contractSNList) {
                ContractPriceAdjustDocEntity doc = new ContractPriceAdjustDocEntity();
                doc.setHandlerSN(user.getUserSN());
                doc.setHandlerName(user.getUserName());
                doc.setHandlerTime(new Date());
                doc.setContractSN(contractSN);
                doc.setSn(queryNewSN(ContractPriceAdjustDocEntity.class));
                doc.setState((short) 2);
                doc.setRemark("根据产品统一调价");
                dao.insertNew(doc);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                var startTimeStr=(String) model.get("startTime");
                var startTime=sdf.parse(startTimeStr);
                //子表
                ContractPriceAdjustmentEntity entity = new ContractPriceAdjustmentEntity();
                var originalPrice=list.stream().filter(t->t.get("contractSN").equals(contractSN)).map(t->Tl.getBigDecimal(t.get("price"))).findFirst();
                entity.setAdjustDocSN(doc.getSn());
                entity.setSn(queryNewSN(ContractPriceAdjustmentEntity.class));
                entity.setStartTime(startTime);
                entity.setOriginalPrice(originalPrice.isPresent()?originalPrice.get().floatValue():0.0F);
                var contractProduct=productsDao.getByContractSNAndProductSN(contractSN,sn);
                entity.setContractProductSN(contractProduct.getSn());
                entity.setCause((String) model.get("cause"));
                if(model.get("modifyPrice") != null){
                    BigDecimal modifyPrice= BigDecimal.valueOf(Double.parseDouble(model.get("modifyPrice").toString()));
                    entity.setModifyPrice(modifyPrice.floatValue());
                    entity.setCurrentPrice(entity.getOriginalPrice()+modifyPrice.floatValue());
                }else if(model.get("adjustScale") != null){
                    BigDecimal adjustScale= BigDecimal.valueOf(Double.parseDouble(model.get("adjustScale").toString()));
                    entity.setAdjustScale(adjustScale.floatValue());
                    entity.setCurrentPrice(entity.getOriginalPrice()*(1+adjustScale.floatValue()/100));
                }else{
                    return -1;
                }
                result=adjustmentDao.insertNew(entity);
            }
        }
        return result;
    }


}